﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web;
using WD.Core.Config;
using WD.Db.Contract;
using WD.Db.Contract.Model;
using WD.Framework.Contract;
using WD.Framework.Utility;
using WD.Framework.Web;

namespace WD.Web.MVC.Common
{

    public abstract class WebControllerBase : WD.Web.ControllerBase
    {
        public WebCookieContext CookieContext
        {
            get
            {
                return WebCookieContext.Current;
            }
        }

        public WebUserContext UserContext
        {
            get
            {
                return WebUserContext.Current;
            }
        }

        public CachedConfigContext ConfigContext
        {
            get
            {
                return CachedConfigContext.Current;
            }
        }

        protected User GetUser(UserRequest request = null)
        {
            var tmp = StaticData.CurrentUser;
            if (tmp == null) return null;
            var model = UserService.GetUser(tmp.ID, request);
            StaticData.CurrentUser = model;
            return model;
        }


        /// <summary>
        /// 获取数据中的分页信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        protected PagerInfo GetPagerInfo<T>(IEnumerable<T> list)
        {
            var tmp = (PagedList<T>)list;
            var pager = new PagerInfo()
            {
                TotalItemCount = tmp.TotalItemCount,
                CurrentPageIndex = tmp.CurrentPageIndex,
                EndRecordIndex = tmp.EndRecordIndex,
                ExtraCount = tmp.ExtraCount,
                PageSize = tmp.PageSize,
                StartRecordIndex = tmp.StartRecordIndex,
                TotalPageCount = tmp.TotalPageCount
            };
            return pager;
        }
        /// <summary>
        /// 递归生成ZtreeNode上下级关系
        /// 将查询出来的任何 list 集合 转换成 ZtreeNode 集合
        /// var tmpZtreeList = list.Select(x => new ZtreeNode()
        /// {
        ///     id = x.ModelID.ToString(CultureInfo.InvariantCulture),
        ///     pId = x.ParentID.ToString(),
        ///     name = x.ModelName
        /// }).ToList(); 
        /// var resultList = ToZtreeNode(tmpZtreeList, "父级ID");
        /// </summary>
        /// <param name="dataList">转换后的ZtreeNode源数据</param>
        /// <param name="rootId">父级</param>
        /// <returns></returns>
        public List<ZtreeNode> ToZtreeNode(List<ZtreeNode> dataList, string rootId)
        {
            var list = dataList.Where(x => x.pId == rootId).ToList();
            var resultList = new List<ZtreeNode>();
            foreach (var row in list)
            {
                var node = row;
                node.children = ToZtreeNode(dataList, node.id);
                resultList.Add(node);
            }
            return resultList;
        }


        /// <summary>
        /// 记录新增日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="url"></param>
        public void LoggerInsert(string message, string url = "")
        {
            Logger(CommonCode.日志类型_新增, message, url);
        }
        /// <summary>
        /// 记录更新日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="url"></param>
        public void LoggerUpdate(string message, string url = "")
        {
            Logger(CommonCode.日志类型_更新, message, url);
        }
        /// <summary>
        /// 记录删除日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="url"></param>
        public void LoggerDelete(string message, string url = "")
        {
            Logger(CommonCode.日志类型_删除, message, url);
        }
        /// <summary>
        /// 记录自定义日志
        /// </summary>
        /// <param name="opTypeCode">日志类型 （CommonCode）</param>
        /// <param name="message">日志内容</param>
        /// <param name="url">复写URL</param>
        public void Logger(int opTypeCode, string message, string url = "")
        {
            var urlTmp = string.IsNullOrWhiteSpace(url)
                        ? (Request.Url != null ? Request.Url.ToString() : "")
                        : url;
            var userId = "";
            var model = new User_OperatLog()
            {
                EditUser = userId,
                OpType = opTypeCode,
                Operating = message,
                Url = urlTmp,
                IP = Fetch.UserIp
            };
            //ServiceContext.Current.User_OperatLogService.SaveUser_OperatLog(model, userId);
        }



        /// <summary>
        /// 用户Token，每次页面都会把这个UserToken标识发送到服务端认证
        /// </summary>
        public virtual Guid UserToken
        {
            get
            {
                return CookieContext.UserToken;
            }
        }

        /// <summary>
        /// 登录后用户信息
        /// </summary>
        public virtual Rbac_LoginInfo LoginInfo
        {
            get
            {
                return UserContext.LoginInfo;
            }
        }

        /// <summary>
        /// 登录后用户信息里的用户权限
        /// </summary>
        public virtual List<string> PermissionList
        {
            get
            {
                var permissionList = new List<string>();

                if (this.LoginInfo != null)
                {
                    permissionList = this.LoginInfo.BusinessPermissionList;
                }

                return permissionList;
            }
        }

        #region Override controller methods
        /// <summary>
        /// 方法执行前，如果没有登录就调整到Passport登录页面，没有权限就抛出信息
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var noAuthorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeIgnoreAttribute), false);
            if (noAuthorizeAttributes.Length > 0)
                return;

            base.OnActionExecuting(filterContext);
            //
            //            if (LoginInfo == null)
            //            {
            //                var url = filterContext.HttpContext.Request.Url != null
            //                                    ? filterContext.HttpContext.Request.Url.AbsolutePath.ToLower()
            //                                    : "";
            //                if (url == "/home/index" || url == "/" || url == "/basearea/home" || url == "/basearea")
            //                {
            //                    //首页未登录则返回登录页面 
            //                  //  filterContext.Result = RedirectToAction("Login", "Auth", new { Area = "BaseArea" });
            //                }
            //                else if (url == "/manager/home" || url == "/manager")
            //                {
            //                    //首页未登录则返回登录页面 
            //                   // filterContext.Result = RedirectToAction("Login", "Auth", new { Area = "Manager" });
            //                }
            //                else
            //                {
            //                    filterContext.Result = new JsonResult
            //                    {
            //                        Data = new
            //                        {
            //                            statusCode = CommonCode.Json结果代码_statusCode_登录超时,
            //                            message = "登录超时，请重新登录！",
            //                            callbackType = CommonCode.Json结果代码_callbackType_关闭当前对话框
            //                        },
            //                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
            //                    };
            //                }
            //            }

            #region 权限判断 已提取到拦截器

            //            bool hasPermission = true;
            //            var permissionAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>();
            //            permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>().Union(permissionAttributes);
            //            var attributes = permissionAttributes as IList<PermissionAttribute> ?? permissionAttributes.ToList();
            //            if (permissionAttributes != null && attributes.Count() > 0)
            //            {
            //                hasPermission = true;
            //                foreach (var attr in attributes)
            //                {
            //                    foreach (var permission in attr.Permissions)
            //                    {
            //                        if (!this.LoginInfo.BusinessPermissionList.Contains(permission))
            //                        {
            //                            hasPermission = false;
            //                            break;
            //                        }
            //                    }
            //                }
            //
            //                if (!hasPermission)
            //                {
            //                    if (Request.UrlReferrer != null)
            //                        filterContext.Result = this.Stop("没有权限！", Request.UrlReferrer.AbsoluteUri);
            //                    else
            //                        filterContext.Result = Content("没有权限！");
            //                }
            //            }

            #endregion
        }

        /// <summary>
        /// 方法后执行后注入一些视图数据
        /// </summary>
        /// <param name="filterContext">filter context</param>
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.ActionDescriptor.ActionName.Contains("Edit") ||
                filterContext.ActionDescriptor.ActionName.Contains("Add"))
                return;

            RenderViewData();
        }

        /// <summary>
        /// 如果是Ajax请求的话，清除浏览器缓存
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
                filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
                filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                filterContext.HttpContext.Response.Cache.SetNoStore();
            }

            base.OnResultExecuted(filterContext);
        }

        /// <summary>
        /// 注入资源，权限，城市等信息
        /// </summary>
        protected override void RenderViewData()
        {
            //var permissions = string.Join(",", this.PermissionList);
            //this.ViewData["permissions"] = permissions;
        }

        #endregion

    }
}
